﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Win32;
using System.IO;


// Retreives Application information
    public class ApplicationInfo
    {  
        public InstalledAppList getInstalledApplications()
        {             
            try
            {
                // List for Applications
                InstalledAppList list = new InstalledAppList();
                List<App> appList = new List<App>();
                // registry path which has information of software installd on machine
                string registryKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
               // go through registry keys to get information needed
                using (Microsoft.Win32.RegistryKey key =  Registry.LocalMachine.OpenSubKey(registryKey))
                {                   
                    var query = from a in key.GetSubKeyNames() let r = key.OpenSubKey(a)
                                select new App
                                {
                                    // get the key name
                                    Name = (string)r.GetValue("DisplayName"),
                                    // get the keys install location
                                    Path = (string)r.GetValue("InstallLocation")
                                };
                    // add to list and return results
                    foreach (var item in query)
                    {
                        if (item.Name != null)
                        {
                            appList.Add(item);
                        }
                    }
                    list.appList = appList;
                    // to InstalledAppList
                    return list;;
                }
            }
            // if above throws exception write error to 'Error2.txt'
            catch (Exception ex)
            {
                StreamWriter sw = new StreamWriter(@"C:\Test\Error2.txt");
                sw.WriteLine(ex.Message);
                sw.WriteLine("\n\n" + ex.InnerException);
                sw.WriteLine("\n\n" + ex.StackTrace);
                sw.WriteLine(ex.Data);                
                sw.Close();
                throw;
            }           
        }
	}	

